//
//  ZTDSearchViewController.m
//  DoctorFAQs
//
//  Created by zjq on 17/3/10.
//  Copyright © 2017年 zjq. All rights reserved.
//

#import "ZTDSearchViewController.h"
#import "SearchTableViewCell.h"
#import "ZSearchHeadCell.h"

#import "ZTacticsTableViewCell.h" 
#import "ZFMDBTool.h"
#import "ZSearchTakeModel.h"

#import "ZTacticsDetailViewController.h"
//#import "ZCVModel.h"
//#import "ZillFModel.h"
#import "LZTacticsModel.h"
#import "DoctorModel.h"
#import "SPPlaceholderCell.h"
static NSString *const placeCellID = @"placeholders";
static NSString * const kJTacSearchIdentifier = @"kJTacSearchTableViewIdentifier";
static NSString * const kJSearchHeaderIdentifier = @"kJTacSearchHeaderCellTableViewIdentifier";
static NSString * const kJTacSearchLookFriendIdentifier = @"kJTacSearchLookFriendIdentifier";
static int page = 1;
@interface ZTDSearchViewController () <UITableViewDataSource,UITableViewDelegate,SearchCleanDelegate,UISearchBarDelegate> {
    NSMutableArray * _dataArray;
}
@property (nonatomic,strong) UIView * titleView;
@property (nonatomic,strong) UITableView * searchHistoryView;
@property (nonatomic,assign) BOOL  isSearch;
@property (nonatomic,strong) NSString * sString; // 搜索文本
@property (nonatomic,strong) NSMutableArray <DoctorModel *> * cvModelArray;
@property (nonatomic,strong) NSMutableArray <LZTacticsModel *> *
zIllModelArray;
@property (nonatomic,strong) UISearchBar *searchBar;
@property (nonatomic,strong) LZUserInfo * userInfo;
@property (nonatomic,assign) BOOL isHaveData; 
@end

@implementation ZTDSearchViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    _isSearch = YES;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initialzeDatas];
    [self initlizeInterface];
}
- (void)initialzeDatas {
    _dataArray = [@[] mutableCopy];
    _isSearch = YES;
    _sString = @"";
    self.isHaveData = YES;
    self.userInfo = [LZUserInfo getUserInfo];
    self.cvModelArray = [NSMutableArray array];
    self.zIllModelArray = [NSMutableArray array];
    [self foundDataBank];
    [self find];
    [self.searchHistoryView reloadData];
}

- (void)initlizeInterface {
    self.view.backgroundColor = MYGRAYCOLOR;
    _searchBar = [[UISearchBar alloc] init];
    _searchBar.delegate = self;
    _searchBar.frame = CGRectMake(0, 0, 130, 35);
    _searchBar.barTintColor = [UIColor whiteColor];
    _searchBar.placeholder = @"搜索关键字";
    _searchBar.backgroundImage = [UIImage imageNamed:@"index_banner"];
    _searchBar.searchBarStyle =  UISearchBarStyleMinimal;
    _searchBar.showsCancelButton = YES;
    for (UIView *view in [[_searchBar.subviews lastObject] subviews]) {
        if ([view isKindOfClass:[UIButton class]]) {
            UIButton *cancelBtn = (UIButton *)view;
            [cancelBtn setTitle:@"搜索" forState:UIControlStateNormal];
        }
    }
    self.navigationItem.titleView = _searchBar;
    [self.view addSubview:self.searchHistoryView];
    [self.searchHistoryView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    
}

-(void)foundDataBank; {
    [[ZFMDBTool sharedInstance] execSqlInFmdb:@"DoctorFAQs" dbFileName:@"search.sqlite" dbHandler:^(FMDatabase *Z_db) {
        NSString *cSql = @"CREATE TABLE IF NOT EXISTS search (id INTEGER PRIMARY KEY, zuserID TEXT NOT NULL, takeString TEXT NOT NULL)";
        BOOL res = [Z_db executeUpdate:cSql];
        if (!res) {
            NSLog(@"error when creating db table");
        } else {
            NSLog(@"succ to creating db table");
        }
    }];
}

// 表格视图协议
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if (_isSearch) {
        return 2;
    }else {
        return 1;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if(_isSearch){
        if (section == 0) {
            if (_dataArray.count == 0) {
                return 0;
            }
            return 1;
        }
        if (section == 1 && _dataArray.count <= 5) {
            return _dataArray.count;
        }
        return 5;
    }else {
//         return (self.cvModelArray && self.cvModelArray != 0)? self.cvModelArray.count : 0;
        return self.isHaveData ? self.cvModelArray.count : 1;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.isSearch) {
        if (indexPath.section == 0) {
            return 45*ysIZE;
        }
        return 55*ysIZE;
    }else {
        if (self.isHaveData == YES) {
            return 270*ysIZE;
        }else {
            return  SCREEN_Height-104;
        }
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (_isSearch) {
        if (indexPath.section == 0) {
            __weak typeof(self) weakSelf = self;
            ZSearchHeadCell * cell = [tableView dequeueReusableCellWithIdentifier:kJSearchHeaderIdentifier forIndexPath:indexPath];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.ZSearchDeleteBlock = ^() {
                [weakSelf  resetButtonAction];
            };
            return cell;
        } else {
            SearchTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:kJTacSearchIdentifier forIndexPath:indexPath];
            cell.contextLabel.text = _dataArray[indexPath.row];
            cell.btnIndex  = indexPath.row;
            cell.SearchDelegate = self;
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            return cell;
        }
    } else {
        if (self.isHaveData == YES) {
            ZTacticsTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:kJTacSearchLookFriendIdentifier forIndexPath:indexPath];
                    cell.selectionStyle = 0;
                    cell.doctorModel = self.cvModelArray[indexPath.row];
                    cell.tacticsModel = self.zIllModelArray[indexPath.row];
                    cell.selectionStyle = UITableViewCellSelectionStyleNone;
                    return cell;
        }else {
            SPPlaceholderCell *cell = [tableView dequeueReusableCellWithIdentifier:placeCellID];
            return cell;
        }
    }
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
//    if (_isSearch ==NO ) {
//        [self jumpZTacDatailVC];
//    }else if (_isSearch == YES) {
//        self.isSearch = NO;
//        _sString = _dataArray[indexPath.row];
//        [self.searchBar resignFirstResponder];
//        [self searchNetWorkingWithTitle:_sString];
//    }
    if (self.isSearch == NO) {
        if (self.isHaveData == NO) {
            return;
        }
        [self jumpZTacDatailVCWith:indexPath.row];
    }else if (self.isSearch == YES) {
        self.isSearch = NO;
        _sString = _dataArray[indexPath.row];
        self.searchBar.text = _sString;
        [self.searchBar resignFirstResponder];
        [self searchNetWorkingWithTitle:_sString];
    }
}
// 进入搜索就医策略详情
- (void)jumpZTacDatailVCWith:(NSInteger) row{
    ZTacticsDetailViewController * ZTDVC = [[ZTacticsDetailViewController alloc] init];
    ZTDVC.artId = _zIllModelArray[row].artID;
    [self .navigationController pushViewController:ZTDVC animated:YES];
}


//searchBar delegate// 开始搜索
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
    if ([searchBar.text isEqualToString:@""]) {
        [YJProgressHUD showMessage:@"输入内容不能为空" inView:self.view];
        return;
    }
   
    [self filterBySubstring:searchBar.text];
    [searchBar resignFirstResponder];
    _isSearch = NO;
    self.isSearch = NO;
    _sString = searchBar.text;
    [self searchNetWorkingWithTitle:_sString];
    
}
//点击键盘上的搜索
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    if ([searchBar.text isEqualToString:@""]) {
        [YJProgressHUD showMessage:@"输入内容不能为空" inView:self.view];
        return;
    }
    [self filterBySubstring:searchBar.text];
    [searchBar resignFirstResponder];
    _isSearch = NO;
    _sString = searchBar.text;
    [self searchNetWorkingWithTitle:searchBar.text];
}
- (void) filterBySubstring:(NSString*) subStr {
    [self inserctWith:subStr];
    [self find];
    [self.searchHistoryView reloadData];
    
}
- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar {
    _isSearch = YES;
    [self.searchHistoryView reloadData];
    return YES;
}


// 下拉刷新
- (void)searchNetWorkingWithTitle:(NSString * )seachString {
    //    ESWeak(self, sWeakSelf);
    page = 1;
    self.isHaveData = YES;
    NSMutableDictionary * dict = [@{@"p":[NSString stringWithFormat:@"%d",page],@"title":seachString} mutableCopy];
    if (self.userInfo.uid && ![self.userInfo.uid isEqualToString:@""]) {
        [dict setObject:self.userInfo.uid forKey:@"uid"];
    };
    [YJProgressHUD showProgress:@"正在加载" inView:self.view];
    [BaseRequest requestWithMethodResponseJsonByGet:TestURL paramars:dict paramarsSite:@"Index/illFriend" sucessBlock:^(id content) {
        
        NSDictionary * idict = [NSJSONSerialization JSONObjectWithData:content options:NSJSONReadingMutableContainers error:nil];
        if ([dict [@"code"] intValue] == 1) {
            [YJProgressHUD showMessage:@"加载成功" inView:self.view];
            [self handleDataWithArray:idict[@"list"]];
        }else {
            self.isHaveData = NO;
            [YJProgressHUD showMessage:@"加载失败" inView:self.view];
            [self.searchHistoryView reloadData];
        }
        
    } failure:^(NSError *error) {
        self.isHaveData = NO;
        [YJProgressHUD showMessage:@"网络请求错误" inView:self.view];
        [self.searchHistoryView reloadData];
    }];
}

- (void)handleDataWithArray:(NSArray *)array {
    
    [self.searchHistoryView.mj_footer resetNoMoreData];
    [self.cvModelArray removeAllObjects];
    [self.zIllModelArray removeAllObjects];
    if (array.count == 0) {
        [YJProgressHUD showMessage:@"已无更多案例" inView:self.view];
        [self.searchHistoryView.mj_footer endRefreshingWithNoMoreData];
        self.isHaveData = NO;
    }else if (array.count < 10) {
        [YJProgressHUD showMessage:@"刷新成功" inView:self.view];
        [self.searchHistoryView.mj_footer endRefreshingWithNoMoreData];
    }
    for (NSDictionary * dict in array) {
        DoctorModel * vcModel = [[DoctorModel alloc] initWithDict:[dict mutableCopy]];
        LZTacticsModel * illModel = [[LZTacticsModel alloc] initWithDict:[dict mutableCopy]];
        [self.cvModelArray addObject:vcModel];
        [self.zIllModelArray addObject:illModel];
    }
    [self.searchHistoryView reloadData];
}
// 上啦加载
- (void)MoresearchNetWorkingWithTitle:(NSString * )string {
    page ++;
    NSMutableDictionary * dict = [@{@"p":[NSString stringWithFormat:@"%d",page],@"title":string} mutableCopy];
    if (self.userInfo.uid && ![self.userInfo.uid isEqualToString:@""]) {
        [dict setObject:self.userInfo.uid forKey:@"uid"];
    }
    [YJProgressHUD showProgress:@"正在加载" inView:self.view];
    
    [BaseRequest requestWithMethodResponseJsonByGet:TestURL paramars:dict paramarsSite:@"Index/illFriend" sucessBlock:^(id content) {
        NSDictionary * idict = [NSJSONSerialization JSONObjectWithData:content options:NSJSONReadingMutableContainers error:nil];
        if ([dict [@"code"] intValue] == 1) {
            [YJProgressHUD showMessage:@"加载成功" inView:self.view];
            [self MorehandleDataWithDict:idict[@"list"]];
        }else {
            
            [YJProgressHUD showMessage:@"加载失败" inView:self.view];
            
        }
    } failure:^(NSError *error) {
        
        [YJProgressHUD showMessage:@"网络请求错误" inView:self.view];
        
    }];
}
- (void)MorehandleDataWithDict:(NSArray *)array {
    [self.searchHistoryView.mj_footer resetNoMoreData];
    if (array.count == 0) {
        [YJProgressHUD showMessage:@"已无更多案例" inView:self.view];
        [self.searchHistoryView.mj_footer endRefreshingWithNoMoreData];
        return;
    }else if (array.count < 10) {
        [YJProgressHUD showMessage:@"刷新成功" inView:self.view];
        [self.searchHistoryView.mj_footer endRefreshingWithNoMoreData];
    }
    for (NSMutableDictionary * dict in array) {
        DoctorModel * vcModel = [[DoctorModel alloc] initWithDict:dict];
        LZTacticsModel * illModel = [[LZTacticsModel alloc] initWithDict:dict];
        [self.cvModelArray addObject:vcModel];
        [self.zIllModelArray addObject:illModel];
    }
    [self.searchHistoryView reloadData];
}
// 数据库部分
// 插入
- (void)inserctWith:(NSString *)string {
    [[ZFMDBTool sharedInstance] execSqlInFmdb:@"DoctorFAQs" dbFileName:@"search.sqlite" dbHandler:^(FMDatabase *Z_db) {
        if ([self tJudgeString:string]) {
            
        }else {
            NSString * sql = @"insert into search (zuserID, takeString) values(?, ?)";
            BOOL res = [Z_db executeUpdate:sql, string, @"1"];
            if (!res) {
                NSLog(@"error to insert data");
            } else {
                NSLog(@"succ to insert data");
            }
        }
    }];
    
}
- (BOOL)tJudgeString:(NSString *)string {
    for (NSString * locaString in _dataArray) {
        if ([string isEqualToString:locaString]) {
            return YES;
        }
    }
    return NO;
}
// 查询
- (void)find {
    [[ZFMDBTool sharedInstance] execSqlInFmdb:@"DoctorFAQs" dbFileName:@"search.sqlite" dbHandler:^(FMDatabase *Z_db) {
        NSString *qSql = @"SELECT * FROM search";
        FMResultSet *set = [Z_db executeQuery:qSql];
        [_dataArray removeAllObjects];// 先移除；
        while ([set next]) {
            
            NSString *name = [set stringForColumn:@"zuserID"];
            NSString *ID_No = [set stringForColumn:@"takeString"];
            NSLog(@"zzzzname%@-- zzid%@--",name,ID_No);
            [_dataArray insertObject:name atIndex:0];
        }

    }];
    
}
// 删除某一行数据
- (void)deleteWith:(NSString *)string {
    [[ZFMDBTool sharedInstance] execSqlInFmdb:@"DoctorFAQs" dbFileName:@"search.sqlite" dbHandler:^(FMDatabase *Z_db) {
        NSString * dsql = @"DELETE FROM search WHERE  zuserID= ?";
        BOOL res = [Z_db executeUpdate:dsql,string];
        if (!res) {
            NSLog(@"error to DELETE data");
        } else {
            NSLog(@"succ to DELETE data");
            [self find];
            [self.searchHistoryView reloadData];
        }
    }];
}
// 删除整个表的数据但不删除表
- (void)deleteTableAllData {
    [[ZFMDBTool sharedInstance] execSqlInFmdb:@"DoctorFAQs" dbFileName:@"search.sqlite" dbHandler:^(FMDatabase *Z_db) {
        NSString * dsql = @"DELETE FROM search";
        BOOL res = [Z_db executeUpdate:dsql];
        if (!res) {
            NSLog(@"error to DELETE data");
        } else {
            NSLog(@"succ to DELETE data");
            [self find];
            [self.searchHistoryView reloadData];
        }
    }];
}



// 头部 清除按钮
- (void)resetButtonAction {
    [self deleteTableAllData];
}
// cell 按钮的方法
- (void)deleteWithBtnindex:(NSInteger)index {
    [self deleteWith:_dataArray[index]];
    [self.searchHistoryView reloadData];
}

//lazy
- (UITableView *)searchHistoryView {
    if (_searchHistoryView) {
        return _searchHistoryView;
    }
    _searchHistoryView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    _searchHistoryView.dataSource = self;
    _searchHistoryView.delegate = self;
    _searchHistoryView.rowHeight = 55*ysIZE;
    [_searchHistoryView registerClass:[SearchTableViewCell class] forCellReuseIdentifier:kJTacSearchIdentifier];
    [_searchHistoryView registerClass:[ZSearchHeadCell class] forCellReuseIdentifier:kJSearchHeaderIdentifier];
    [_searchHistoryView registerClass:[ZTacticsTableViewCell class] forCellReuseIdentifier:kJTacSearchLookFriendIdentifier];
    
    _searchHistoryView.backgroundColor = MYGRAYCOLOR;
    
    _searchHistoryView.tableFooterView = [UIView new];
    return _searchHistoryView;
}
- (void)setIsSearch:(BOOL)isSearch {
    _isSearch = isSearch;
    if (_isSearch == NO) {
        self.searchHistoryView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            [self searchNetWorkingWithTitle:_sString];
            [self.searchHistoryView.mj_header endRefreshing];
        }];
        self.searchHistoryView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
            [self MoresearchNetWorkingWithTitle:_sString];
            [self.searchHistoryView.mj_footer endRefreshing];
        }];
        self.isHaveData = NO;
        
    }else {
        self.searchHistoryView.mj_header = nil;
        self.searchHistoryView.mj_footer = nil;
        [self.searchHistoryView reloadData];
    }

}
@end
